package com.yupi.myapigateway.filter;

import cn.hutool.json.JSONUtil;
import com.google.common.util.concurrent.RateLimiter;
import com.vvv.myapiclientsdk.model.request.UserRequest;
import com.vvv.myapiclientsdk.utils.SignUtils;
import com.yupi.model.entity.InterfaceInfo;
import com.yupi.model.entity.User;
import com.yupi.service.InnerInterfaceInfoService;
import com.yupi.service.InnerUserInterfaceInfoService;
import com.yupi.service.InnerUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

/**
 * @author vvv
 * @date 2023-10-02 17 39
 * discription
 */
@Slf4j
@Component
public class CustomGlobalFilter implements GlobalFilter, Ordered {

    @DubboReference
    private InnerUserService innerUserService;

    @DubboReference
    private InnerInterfaceInfoService innerInterfaceInfoService;

    @DubboReference
    private InnerUserInterfaceInfoService innerUserInterfaceInfoService;

    @Resource
    private RateLimiter rateLimiter;

    // 白名单
    public static final HashSet<String> WITHE_LIST = new HashSet<>(Arrays.asList("127.0.0.1"));

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 1. 限流
        //限流过滤
        if (!rateLimiter.tryAcquire()) {
            log.error("请求太频繁了，被限流了!!!");
            return handleInvokeError(response);
        }

        // 1. 请求日志
        log.info("请求唯一表示: " + request.getId());
        String url = request.getURI().toString();
        log.info("请求路径: " + url);
        String method = request.getMethod().toString();
        log.info("请求方法: " + method);
        log.info("请求参数: " + request.getQueryParams());
        String sourceAddress = request.getLocalAddress().getHostString();
        log.info("请求源地址: " + sourceAddress);
        // 2. 黑白名单
        if (!WITHE_LIST.contains(sourceAddress)) {
            return handleNOAuth(response);
        }
        // 3. 用户鉴权（判断ak，sk 是否合法）
        HttpHeaders headers = request.getHeaders();
        String accessKey = headers.getFirst("accessKey");
        String sign = headers.getFirst("sign");
        String timestamp = headers.getFirst("timestamp");
        String nonce = headers.getFirst("nonce");
        String body = headers.getFirst("body");
        String interfaceToken = headers.getFirst("interfaceToken");
        // 参数检验
        // 1. 判空
        if (StringUtils.isAnyBlank(accessKey, sign, timestamp, nonce, interfaceToken)) {
            return handleNOAuth(response);
        }

        // 2. 判断timestamp
        // 超过5分钟过期
        final long FIVE_MINUTES = 60 * 5L;
        long currentTime = System.currentTimeMillis() / 1000;
        if (currentTime - Long.valueOf(timestamp) >= FIVE_MINUTES) {
            return handleNOAuth(response);
        }
        // 3. 判断nonce
        // 在redis 或者 session中存查看传过来的nonce是否在后端存在过
        if (Long.valueOf(nonce) > 10000L) {
            return handleNOAuth(response);
        }

        // 4. 判断ak
        //去数据库查找ak, 如果早不到ak，则无权限
        User user = null;
        try {
            user = innerUserService.getUserByAk(accessKey);
        } catch (Exception e) {
            log.error("innerUserService.getUserByAk() error" + e);
        }
        if (user == null) {
            return handleNOAuth(response);
        }
        // 5. 判断sign
        String secreteKey = user.getSecreteKey();
        // TODO 这个加密算法有点慢
        String serveSign = SignUtils.getSign(body, secreteKey);
        if (!serveSign.equals(sign)) {
            return handleNOAuth(response);
        }
        // 4. 请求模拟接口是否存在？
        // 通过url和method远程调用去数据库查接口
        InterfaceInfo interfaceInfo = null;
        try {
            interfaceInfo = innerInterfaceInfoService.getInterfaceInfoBySDKToken(interfaceToken);
        } catch (Exception e) {
            log.error("innerInterfaceInfoService.getInterfaceInfoById() error" + e);
        }
        if (interfaceInfo == null) {
            return handleNOAuth(response);
        }
        // 5. 查看用户剩余调用次数是否>0
        int leftInvokeNum = 0;
        try {
            leftInvokeNum = innerUserInterfaceInfoService.getLeftInvokeNum(interfaceInfo.getId(), user.getId());
        } catch (Exception e) {
            log.error("innerUserInterfaceInfoService.getLeftInvokeNum() error" + e);
        }
        if (leftInvokeNum <= 0) {
            return handleNOAuth(response);
        }
        // 6. 请求转发，调用模拟接口
        // 7. 响应日志
        return handleResponse(exchange, chain, interfaceInfo.getId(), user.getId());
    }

    /**
     * 主要通过ServerHttpResponseDecorator 修饰了response
     * 当处理完请求后，自动回调修饰者里面的writeWith方法
     * 所以我们可以在writeWith 方法里面写一些调用完的逻辑
     * @param exchange
     * @param chain
     * @return
     */
    public Mono<Void> handleResponse(ServerWebExchange exchange, GatewayFilterChain chain,
                                     long interfaceInfoId, long userId) {
        try {
            // 获得原始的响应对象
            ServerHttpResponse originalResponse = exchange.getResponse();
            DataBufferFactory bufferFactory = originalResponse.bufferFactory();
            // 获得响应的状态码
            HttpStatus statusCode = originalResponse.getStatusCode();

            if(statusCode == HttpStatus.OK){
                // 创建一个修饰后的响应对象
                ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {

                    // 重写writeWith方法，当我们的模拟接口调用完成后，
                    // 就会调用writeWith方法，我们就能根据响应结果做一些自己的处理
                    @Override
                    public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                        //log.info("body instanceof Flux: {}", (body instanceof Flux));
                        if (body instanceof Flux) {
                            Flux<? extends DataBuffer> fluxBody = Flux.from(body);
                            // 返回一个处理后的响应体 （这里可以理解为它在字符串拼接，把缓冲的数据取出来，一点一点拼好）
                            return super.writeWith(fluxBody.map(dataBuffer -> {
                                // 8. 调用成功，接口调用次数 + 1
                                try {
                                    innerUserInterfaceInfoService.invokeCount(interfaceInfoId, userId);
                                } catch (Exception e) {
                                    log.error("innerUserInterfaceInfoService.invokeCount() error" + e);
                                }
                                byte[] content = new byte[dataBuffer.readableByteCount()];
                                dataBuffer.read(content);
                                DataBufferUtils.release(dataBuffer);//释放掉内存
                                // 构建日志
                                StringBuilder sb2 = new StringBuilder(200);
                                List<Object> rspArgs = new ArrayList<>();
                                rspArgs.add(originalResponse.getStatusCode());
                                //rspArgs.add(requestUrl);
                                // 这个就是响应体的内容（返回值）
                                String data = new String(content, StandardCharsets.UTF_8);//data
                                sb2.append(data);
                                // 打印日志
                                log.info("响应结果：" + data);
                                return bufferFactory.wrap(content);
                            }));
                        } else {
                            log.error("<--- {} 响应code异常", getStatusCode());
                        }
                        return super.writeWith(body);
                    }
                };
                // 对于200 OK的请求，将装饰后的响应对象传递给下一个过滤器链（设置response对象为装饰过的）
                return chain.filter(exchange.mutate().response(decoratedResponse).build());
            }
            return chain.filter(exchange);//降级处理返回数据
        }catch (Exception e){
            log.error("网关处理响应异常" + e);
            return chain.filter(exchange);
        }
    }

    /**
     *  没有权限，返回错误码403
     * @param response
     * @return
     */
    private Mono<Void> handleNOAuth(ServerHttpResponse response) {
        response.setStatusCode(HttpStatus.FORBIDDEN);
        return response.setComplete();
    }

    /**
     *  调用失败，返回错误码500
     * @param response
     * @return
     */
    private Mono<Void> handleInvokeError(ServerHttpResponse response) {
        response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
